// @ts-ignore
import axios from "axios"
import router from '@/router'
import {useUserInfo} from "@/stores"
import {useNotification} from 'naive-ui'

const notification = useNotification()

const enum ResponseState {
  success = 200,        //得到正确响应
  beOverdue = 301,      //token 失效
}

// 创建axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 60000
})

// 请求异常消息节流
let timesArr: string[] = []
const fn_msgFirstTime = (name: string, duration = 2000) => {
  if (timesArr.includes(name)) return false
  timesArr.push(name)
  setTimeout(() => {
    timesArr = []
  }, duration)
  return true
}

const pathArr = ['/login/auth', '/kaptcha/get']
const Store = useUserInfo()
// http请求拦截器
service.interceptors.request.use((config: any) => {
    // 进度条开启
    window.$loadingBar.start()

    const METHOD = config.method.toLocaleUpperCase()
    if (METHOD === 'GET') {
      if (!config.params || !Object.keys(config.params).length) {
        if (config.data && Object.keys(config.data).length) {
          config.params = config.data
        }
      }
      delete config.data
    }

    // 在发送请求之前做些什么
    if (!pathArr.includes(config.url as string)) {
      if (Store.token) {
        // 判断是否存在token，如果存在的话，则每个http header都加上token
        config.headers["token"] = Store.token
      }
    }
    return config
  }, (error: any) => {
    window.$message.error('请求超时');
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use((response) => {
    // 进度条完成
    window.$loadingBar.finish()
    // 对响应数据做点什么
    const res = response.data
    if (res.code == ResponseState.beOverdue) {
      window.$message.error('登录失效，请重新登录');
      Store.$reset()
      router.push({path: '/login'})
      return
    }
    if (res.code !== ResponseState.success) {
      window.$notification.error({
        content: '错误',
        meta: res.message,
        duration: 2500,
        keepAliveOnHover: true
      })
      return Promise.reject(res)
    }
    return res
  }, (error: any) => {
    console.log('error ==', error)
    window.$loadingBar.finish()
    const res = error.response && error.response.data
    const state = res && res.code
    if (!error.response) {
      if (fn_msgFirstTime('network')) {
        window.$message.error('请求超时，请检查网络');
      }
      return Promise.reject(error)
    }
    if (state == ResponseState.beOverdue) {
      if (fn_msgFirstTime('login')) {
        window.$message.error('登录失效，请重新登录');
      }
      Store.$reset()
      router.push({path: '/login'})
      return Promise.reject(error)
    }

    if (fn_msgFirstTime('error')) {
      window.$notification.error({
        content: '服务出现异常',
        meta: res.message,
        duration: 2500,
        keepAliveOnHover: true
      })
    }
    return Promise.reject(error)
  }
)

export default service